var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var ballList = new Array();


function Ball() {
  this.size = 12;
  var radom = Math.random;
  // parseInt(Math.random() * 255)
  this.color = 'rgb(' + parseInt(Math.random() * 255) + ',' + parseInt(Math.random() * 255) + ',' + parseInt(Math.random() * 255) + ')';
  this.velX = radom() * 5;
  this.velY = radom() * 5;
  this.x = this.size + radom() * (api.getDomWidth() - this.size);
  this.y = this.size + radom() * (api.getDomHeigh() - this.size);
  this.isRemove = false;
}
var api = {
  getDomWidth: function () {
    return canvas.width;
  },
  setDomWidth: function () {
    canvas.width = window.innerWidth;
  },
  getDomHeigh: function () {
    return canvas.height;
  },
  setDomHeigh: function () {
    canvas.height = window.innerHeight;
  },
  draw: function () {
    ctx.beginPath();
    ctx.fillStyle = this.color;
    ctx.arc(parseInt(this.x), parseInt(this.y), this.size, 0, 2 * Math.PI);
    ctx.fill();
  },
  updated: function () {
    if ((this.x + this.size) >= this.getDomWidth()) {
      this.x = api.getDomWidth() - this.size
      this.velX = -(this.velX);
    }
    if ((this.x - this.size) <= 0) {
      this.x = this.size;
      this.velX = -(this.velX);
    }
    if ((this.y + this.size) >= this.getDomHeigh()) {
      this.y = api.getDomHeigh() - this.size
      this.velY = -(this.velY);
    }
    if ((this.y - this.size) < 0) {
      this.y = this.size;
      this.velY = -(this.velY);
    }
    this.x += this.velX;
    this.y += this.velY;
  },
  collisionDetect: function () {
    for (var i = 0; i < ballList.length; i++) {
      var ball = ballList[i];
      if (this !== ball) {
        if ((Math.sqrt(this.x - ball.x) + Math.sqrt(this.y - ball.y)) < Math.sqrt(2*this.size)) {
          this.velY = -(this.velY);
          this.velX = -(this.velX);
          this.color=ball.color;
        }
      }
    }
  }
}
Ball.prototype = api;
window.onload = function () {
  api.setDomHeigh();
  api.setDomWidth();
  loop(true);
}
window.onresize = function () {
  api.setDomHeigh();
  api.setDomWidth();
}
function loop(isLoop) {
  ctx.fillStyle = 'rgba(0, 0, 0, 0.25)';
  ctx.fillRect(0, 0, api.getDomWidth(), api.getDomHeigh());
  while (ballList.length < 25) {
    ballList.push(new Ball());
  }
  for (var i = 0; i < ballList.length; i++) {
    ballList[i].updated();
    ballList[i].collisionDetect()
    ballList[i].draw();
  }
  if (isLoop) {
    requestAnimationFrame(loop);
  }
}